<template>
    <div class="contract">
        <template v-if="isPc">
            <!--  class="flexR-Cen" -->
            <div id="contractTitle" class="title flexR-Cen">
                <div class="title-div flexR-Cen">
                    <el-image class="image" :src="img3" fit="cover" />
                    <span>{{ detailData.gcmc || contractData?.projectName }} 下游合同立项</span>
                </div>
                <div class="yichu flexR-FS-C">
                    <p class="mr10 flexR-FS-C"><el-image class="yichu-image" :src="img19" fit="cover" />单位（万元）</p>
                    <span>累计溢出预警：<count-to-number class="color1" :number="detailData.ycyjje" /></span>
                </div>
            </div>

            <div class="card-div flexR-W-FS">
                <div v-for="(item, key, index) in tableDataMap" :key="key" :class="{ 'w100': item.data.length }">
                    <card-box :title="item.name" :img-icon="item.img" :table-data="item.data" :ref-index="item.value"
                        @success="getList" />
                </div>
            </div>

            <div :style="{ marginBottom: totalFixHeight + 'px' }">
                <!-- 签字意见 -->
                <div ref="remarkRef">
                    <el-input class="remarkTitle" placeholder="请输入签字意见" disabled="">
                        <template #prepend><el-button :icon="Edit" /></template>
                    </el-input>
                    <el-input v-model="remark" class="remarkInput" type="textarea" :rows="remarkFocused ? 4 : 2"
                        :maxlength="200" show-word-limit @focus="focusInput" @blur="blurInput" />
                </div>
                <!-- 流程意见 -->
                <elTab-box :details-length="detailsList.length" />
            </div>

            <!-- 悬浮框 -->
            <total-fix v-if="detailsList.length" :remark="remark" @init-height="getTotalFixHeight"
                @submit="handlePrependSave" />
        </template>

        <template v-else>
            <span class="title">{{ detailData.gcmc || contractData?.projectName }} 下游合同立项</span>
            <p class="yichu flexR-FE-C">累计溢出预警：<count-to-number class="color1" :number="detailData.ycyjje" /></p>
            <el-row class="card-div">
                <el-col v-for="(item, key, index) in tableDataMap" :key="key" :span="24">
                    <card-box-mob :title="item.name" :img-icon="item.img" :table-data="item.data"
                        :ref-index="item.value" :detail-data="detailData" @success="getList" />
                </el-col>
            </el-row>

            <!-- 悬浮框 -->
            <total-fix v-if="detailsList.length" @init-height="getTotalFixHeight" @submit="handlePrependSave" />
        </template>
    </div>
</template>

<script setup>
import CardBox from './cardBox.vue'
import CardBoxMob from './cardBoxMob.vue'
import { saveContractInitiationApi, getContractInitiationListApi, submitContractApi } from '@/api/contract'
import ElTabBox from './elTabBox.vue'
import TotalFix from './totalFix.vue'
import commonData from '@/hooks/commonData'
import { scrollTo } from '@/utils/scroll-to'

const { setContractData, getContractData, initAos, AOS, commonsStore, reload, Edit, isPc, img3, img4, img5, img6, img7, img8, img9, img10, img19 } = commonData()

// 底部悬浮框高度
const totalFixHeight = ref(0)

const contractData = ref({})

const detailData = ref({})
const detailsList = ref([])
provide('detailData', detailData)
provide('detailsList', detailsList)

const tableDataMap = ref({
    0: { value: 0, data: [], img: img4, name: '专业分包合同' },
    1: { value: 1, data: [], img: img5, name: '劳务分包合同' },
    2: { value: 2, data: [], img: img6, name: '材料采购合同' },
    3: { value: 3, data: [], img: img7, name: '外加工合同' },
    4: { value: 4, data: [], img: img8, name: '租赁合同' },
    5: { value: 5, data: [], img: img9, name: '技术服务合同' },
    6: { value: 6, data: [], img: img10, name: '其他合同' }
})
const remark = ref('')
const remarkRef = ref(null)
const remarkFocused = ref(false)

onMounted(() => {
    initAos()
    contractData.value = getContractData()
    if (contractData.value.projectName) {
        if (contractData.value.contractInitiationUuId) {
            getList()
        } else {
            handleNoSave()
        }
    }
})

async function getList() {
    for (const key in tableDataMap.value) {
        tableDataMap.value[key].data = []
    }
    const params = {
        uuid: contractData.value.contractInitiationUuId,
        requestId: commonsStore.requestId
    }
    const { data } = (await getContractInitiationListApi(params))
    if (data) {
        detailData.value = data

        // 将原始数组扁平化得到新数组
        if (data.details && data.details.length) {
            detailsList.value = initDetailsList(data.details)

            detailsList.value.forEach(el => {
                // el中只要有一个是审核中，就是审核中
                if (el.lxStatus == 9) {
                    detailData.value.isShenhe = true
                }

                if (tableDataMap.value.hasOwnProperty(el.lxlx)) {
                    tableDataMap.value[el.lxlx].data.push({
                        ...el,
                        isFirstSubmit: detailData.value.isFirstSubmit
                    })
                }
            })
        }
    }
    initAos()
}

function initDetailsList(array) {
    return array.reduce((result, item) => {
        result.push(item)
        if (item.children) {
            result = result.concat(initDetailsList(item.children))
            delete item.children // 如果不需要保留原始数组的结构，可以删除 children 属性
        }
        return result
    }, [])
}

async function handleNoSave() {
    const params = {
        gcbh: contractData.value.projectId,
        kzje: 0,
        lxyt: contractData.value.lxyt
    }
    if (contractData.value.gllxid) {
        params.gllxid = contractData.value.gllxid
    }
    const { data } = await saveContractInitiationApi(params)
    if (data.uuid) {
        contractData.value.contractInitiationUuId = data.uuid
        setContractData({
            contractInitiationUuId: data.uuid
        })
        getList()
    }
}

function getTotalFixHeight(height) {
    totalFixHeight.value = height
}

// 先保存
async function handlePrependSave(kzje) {
    if (kzje) {
        const params = {
            uuid: contractData.value.contractInitiationUuId,
            gcbh: contractData.value.projectId,
            kzje,
            lxyt: contractData.value.lxyt
        }
        const { data } = await saveContractInitiationApi(params)
        if (data.uuid) {
            handleSubmit(data.uuid)
        }
    }
}

// 后提交
async function handleSubmit(uuid) {
    if (uuid) {
        const params = {
            uuid
        }
        const { data } = await submitContractApi(params)
        if (data.requestId) {
            reload()
        }
    }
}

function focusInput() {
    remarkFocused.value = true
    scrollTo(remarkRef.value.offsetTop + 50, 800)
}

function blurInput() {
    remarkFocused.value = false
}
</script>

<style scoped lang='scss'>
@import "./style.scss";

[data-mode="pc"] {
    .contract {
        padding: 10px 20px;
        position: relative;

        .title {
            // height: 70px;
            background: #fff;
            box-shadow: 0 3px 13px 0 rgb(187 187 187 / 12%);
            border-radius: 4px;
            position: relative;
            padding: 10px 0;

            .title-div {
                width: 60%;
                margin-right: 70px;

                .image {
                    width: 47px;
                    margin-right: 10px;
                }

                span {
                    font-size: 18px;
                    line-height: 28px;
                    color: rgb(0 0 0 / 94%);
                    letter-spacing: 1px;
                }
            }

            .yichu {
                position: absolute;
                top: 22px;
                right: 40px;
                font-size: 16px;

                .yichu-image {
                    width: 25px;
                    margin-right: 10px;
                }
            }
        }

        .card-div {
            margin-bottom: 30px;
        }

        .shenhe-img {
            width: 100px;
            position: absolute;
            top: 30px;
            left: 100px;
            z-index: 100;
        }

        .remarkInput {
            transition: all 0.5s;
        }
    }
}

[data-mode="mobile"] {
    .contract {
        padding: 24px 15px 0;
        position: relative;

        .title {
            line-height: 22px;
            font-size: 18px;
            color: #000;
        }

        .yichu {
            font-size: 15px;
            margin: 15px 0 10px;
        }

        .card-div {
            width: 100%;
            margin-bottom: 80px;
        }

        .shenhe-img {
            width: 70px;
            position: absolute;
            top: 40px;
            right: 80px;
            z-index: 100;
        }
    }
}
</style>
